// 1. React核心库
import React, { useState, useEffect } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, Card, Form, Input, InputNumber, Select, Switch, message } from 'antd';

// 4. 专业组件库
import { PageContainer } from '@ant-design/pro-components';

// 5. 路由和状态管理
import { useParams } from '@umijs/max';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { RoleExtension } from '@/services/generated';

const { TextArea } = Input;

const RoleForm: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const isEdit = !!id;

  useEffect(() => {
    if (isEdit && id) {
      const fetchData = async () => {
        try {
          await autoLoginInDev();
          const response = await apiClients.permissions.permissionsRolesRetrieve({ id: parseInt(id) });
          const data = response.data;
          form.setFieldsValue({
            ...data,
            name: data?.group?.name,
          });
        } catch (error) {
          message.error('获取数据失败');
        }
      };
      fetchData();
    }
  }, [id, isEdit, form]);

  const onFinish = async (values: any) => {
    try {
      setLoading(true);
      await autoLoginInDev();

      // 构造请求数据
      const requestData = {
        code: values.code,
        description: values.description,
        level: values.level,
        status: values.status,
        is_system: values.is_system || false,
        group: {
          name: values.name,
        },
      };

      if (isEdit) {
        await apiClients.permissions.permissionsRolesUpdate({ 
          id: parseInt(id!), 
          roleExtensionRequest: requestData as any
        });
        message.success('更新成功');
      } else {
        await apiClients.permissions.permissionsRolesCreate({ 
          roleExtensionRequest: requestData as any
        });
        message.success('创建成功');
      }

      window.location.href = '/permissions/roles';
    } catch (error) {
      message.error(isEdit ? '更新失败' : '创建失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageContainer title={isEdit ? '编辑角色' : '新建角色'}>
      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
          initialValues={{
            status: 'active',
            level: 5,
            is_system: false,
          }}
        >
          <Form.Item
            label="角色名称"
            name="name"
            rules={[
              { required: true, message: '请输入角色名称' },
              { max: 150, message: '角色名称不能超过150个字符' },
            ]}
          >
            <Input placeholder="请输入角色名称" />
          </Form.Item>

          <Form.Item
            label="角色代码"
            name="code"
            rules={[
              { required: true, message: '请输入角色代码' },
              { max: 50, message: '角色代码不能超过50个字符' },
              { pattern: /^[a-z_]+$/, message: '角色代码只能包含小写字母和下划线' },
            ]}
          >
            <Input placeholder="请输入角色代码，如：admin、editor" />
          </Form.Item>

          <Form.Item
            label="角色级别"
            name="level"
            rules={[
              { required: true, message: '请输入角色级别' },
              { type: 'number', min: 1, max: 10, message: '角色级别必须在1-10之间' },
            ]}
          >
            <InputNumber
              min={1}
              max={10}
              placeholder="请输入角色级别（1-10，数字越小权限越高）"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            label="状态"
            name="status"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select
              options={[
                { label: '激活', value: 'active' },
                { label: '禁用', value: 'inactive' },
              ]}
            />
          </Form.Item>

          <Form.Item
            label="系统角色"
            name="is_system"
            valuePropName="checked"
          >
            <Switch checkedChildren="是" unCheckedChildren="否" />
          </Form.Item>

          <Form.Item
            label="描述"
            name="description"
            rules={[
              { max: 500, message: '描述不能超过500个字符' },
            ]}
          >
            <TextArea
              rows={4}
              placeholder="请输入角色描述"
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>
              {isEdit ? '更新' : '创建'}
            </Button>
            <Button style={{ marginLeft: 8 }} href="/permissions/roles">
              取消
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default RoleForm;
